package com.plateno.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ResponseBody;

import com.plateno.bean.model.Config.MsgCode;
import com.plateno.exception.PlatenoException;
import com.plateno.util.JsonUtil;
import com.plateno.util.StringEscapeEditor;
@Service
public abstract class AbstractController {

	
	private static final Logger logger = LoggerFactory.getLogger(AbstractController.class);
	
	public static final String MEMBER_TOKEN = "mid";


	@ExceptionHandler
	@ResponseBody
	public String handle(Exception e, HttpServletRequest request) {
		
		String uri = "";
		String mid = "";
		try {
			uri = request.getRequestURI();
			mid = request.getHeader("mid");
		} catch (Exception e2) {
			logger.error("", e);
		}
		String reqInfo = " (URI=" + uri + " mid=" + mid +") ";
		
		if(e instanceof IOException){
			logger.error("IOException" + reqInfo, e);
			return JsonUtil.generateResponse(e.getMessage(),MsgCode.BAD_REQUEST);
		}else if(e instanceof PlatenoException){
			//logger.warn("业务异常" + reqInfo + e.getMessage(), e);
			return JsonUtil.generateResponse(((PlatenoException) e).getErrorCode(),((PlatenoException) e).getErrorMessage());
		}else if(e instanceof MethodArgumentNotValidException){
			BindingResult result = ((MethodArgumentNotValidException) e).getBindingResult();
			List<ObjectError> list = result.getAllErrors();
			ObjectError oe = list.get(0);
			logger.warn("参数异常:"+ reqInfo + oe.getDefaultMessage(), e);
			return JsonUtil.generateResponse(MsgCode.BAD_REQUEST.getMsgCode(),oe.getDefaultMessage());
		}
		else{
			logger.error("系统异常" + reqInfo, e);
			return JsonUtil.generateResponse(e.getMessage(),MsgCode.SYSTEM_ERROR);
		}
	}
	
	
	/**
	 * 网站sql注入，script注入等的防护。
	 * @param binder
	 */
	@InitBinder
	public void initBinder(WebDataBinder binder,HttpServletRequest request) {
		binder.setAutoGrowCollectionLimit(5000);
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false, false));
	}

	

}
